Kurt Hsu's blog

The Rails developer in taiwan.


  • 首頁

  • 標籤

  • 分類

  • 歸檔

[Rails]專案引入vue & 利用Attribute給 vue 資料

發表於 2018-05-14 更新於 2019-08-22 分類於 Rails , Vue

我的開發環境:
Rails 5.1以上

引入webpacker和vue


先安裝web packer

Gemfile
1
gem 'webpacker', '~> 3.5'

$ bundle install
$ bundle exec rails webpacker:install

可以查看webpacker帶有什麼指令:
$ rails webpacker

比起npm我比較喜歡用yarn:
$ bundle exec webpacker:yarn_install
$ yarn install

有個指令可以直接安裝vue:
$ bundle exec webpacker:install:vue

利用Attribute給 vue 資料


先在contoller設定變數:

products_controller.rb
1
2
3
def index
@products = Product.all
end

再到view裡面把資料帶入DOM:

index.html.erb
1
2
3
4
5
6
<% props = {
products: @products
}.to_json
%>

<div id="app" data="<%= props %>"></div>

接下來到vue的檔案application:

app/javascript/packs/application.js
1
2
3
4
5
6
7
8
9
10
11
12
import Vue from 'vue'
import App from '../app.vue'

document.addEventListener('DOMContentLoaded', () => {
const el = "#app"

const props = JSON.parse($("#app")[0].getAttribute('data'))
const app = new Vue({
el: el,
render: h => h(App, { props })
})
})

最後到vue 的component:

app/javascript/app.vue
1
2
3
4
5
6
7
8
9
10
11
12
13
<script>
export default {
props: ["products"],
data: function () {
return {
message: "Hello Vue!"
}
},
mounted: function () {
console.log("products", products)
}
}
</script>

mounted是vue生成完之後會執行的動做,可以參考vue lifecycle。
如果有console出東西就ok嘍!!

這個方式的優點十分明顯,可以省去製作API和串接的麻煩,但就是比較不彈性,真正要做到完全的前後端分離建議還是分成兩個專案,Rails寫API而Vue去做前端實現。

參考文章:
Passing Props to Vue in a Rails View

# Rails # Vue # attribute
[Rails]rails 搭配 vue-router(目前無法指定vue-routes)
[Rails] I18n 基本使用
  • 文章目錄
  • 本站概要

Kurt Hsu

Progress One Percent Every Day
171 文章
55 分類
163 標籤
RSS
  1. 1. 引入webpacker和vue
  2. 2. 利用Attribute給 vue 資料
© 2020 Kurt Hsu
由 Hexo 強力驅動 v3.8.0
|
主題 – NexT.Muse v7.3.0